import "./index.scss"
import {View, Text} from "@tarojs/components"
import {observer} from "mobx-react"
import {useContext, useEffect, useState} from "react"
import Taro, {useDidHide, useDidShow, useRouter} from "@tarojs/taro"
import {Switch, Picker, Button, Input} from "@tarojs/components"
import {devInfoStore} from "./model"
import {AtSwitch, AtList, AtListItem, AtCheckbox, AtIcon, AtButton, AtInputNumber} from "taro-ui"
import staticData from "./data.json"
import {dpdReadModeApi, dpdReadStatusApi, setDpdDataApi} from "@/api/dpd"
import {getHexByTimes, getTimesFunc, mathTimeFunc} from "./utils"

const DpdControl = () => {
	let router = useRouter()
	// const {updatePageQuery, pageData, updatePageDataSource} = useContext(devInfoStore)

	/* 数据 start -------------------------------------------------------------------------- */

	// 当前设备编号
	const [currentDevGId, setCurrentDevGId] = useState("")

	// 报警状态标识
	const [alarmStatus, setAlarmStatus] = useState(0)

	// 流程开关标识
	const [flowSwitch, setFlowSwitch] = useState(false)

	// 流程开关按钮状态
	const [flowStatus, setFlowStatus] = useState(0)

	// 本次开机时间
	const [startUpTime, setStartUpTime] = useState("----")

	/* 当前测量模式 */
	//  0:手动测量模式   1:连续测量模式    2:整点测量模式
	const [currentMeasureMode, setCurrentMeasureMode] = useState(0)
	const [currentMeasureModeDefault, setCurrentMeasureModeDefault] = useState(0)

	// 连续测量间隔时间（单位：秒 s）
	const [continuousMeasureInterval, setContinuousMeasureInterval] = useState(0)

	// 连续测量间隔时间默认值
	const [continuousMeasureIntervalDefault, setContinuousMeasureIntervalDefault] = useState(0)

	const [checkedList, setCheckedList] = useState([])

	const [checkedListDefault, setCheckedListDefault] = useState([])
	// 所有整点时间
	let timeAll = [
		0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
	]

	// 整点数据选择
	let [timesSelectData, setTimesSelectData] = useState([])

	let checkboxOption = [
		{
			value: 0,
			label: "00:00",
			desc: ""
		},
		{
			value: 1,
			label: "01:00"
		},
		{
			value: 2,
			label: "02:00",
			desc: ""
		},
		{
			value: 3,
			label: "03:00",
			desc: ""
		},
		{
			value: 4,
			label: "04:00",
			desc: ""
		},
		{
			value: 5,
			label: "05:00"
		},
		{
			value: 6,
			label: "06:00",
			desc: ""
		},
		{
			value: 7,
			label: "07:00",
			desc: ""
		},
		{
			value: 8,
			label: "08:00",
			desc: ""
		},
		{
			value: 9,
			label: "09:00",
			desc: ""
		},
		{
			value: 10,
			label: "10:00",
			desc: ""
		},
		{
			value: 11,
			label: "11:00",
			desc: ""
		},
		{
			value: 12,
			label: "12:00",
			desc: ""
		},
		{
			value: 13,
			label: "13:00"
		},
		{
			value: 14,
			label: "14:00",
			desc: ""
		},
		{
			value: 15,
			label: "15:00",
			desc: ""
		},
		{
			value: 16,
			label: "16:00",
			desc: ""
		},
		{
			value: 17,
			label: "17:00"
		},
		{
			value: 18,
			label: "18:00",
			desc: ""
		},
		{
			value: 19,
			label: "19:00",
			desc: ""
		},
		{
			value: 20,
			label: "20:00",
			desc: ""
		},
		{
			value: 21,
			label: "21:00"
		},
		{
			value: 22,
			label: "22:00",
			desc: ""
		},
		{
			value: 23,
			label: "23:00",
			desc: ""
		}
	]

	/* 数据 end -------------------------------------------------------------------------- */

	// 可以使用所有的 React Hooks
	useEffect(() => {
		console.log("Devinfo useEffect")
	})
	// 对应 onShow
	useDidShow(() => {
		console.log("Devinfo useDidShow")
		console.log("param", router.params)
		// setCurrentDevGId(router.params.devGId)
		// 查询数据
		dpdReadStatusFunc()
	})
	// 对应 onHide
	useDidHide(() => {
		console.log("Devinfo useDidHide")
	})

	// 读取状态数据的函数
	const dpdReadStatusFunc = async () => {
		// Taro.showLoading({
		// 	title: "正在加载"
		// })
		// setTimeout(() => {
		// 	Taro.hideLoading()
		// }, 100000)
		console.log("devGId", router.params.devGId)

		let data = {
			devGId: router.params.devGId
		}
		await dpdReadStatusApi(data)
			.then(res => {
				console.log("读取状态数据res", res)
				setAlarmStatus(res.data.warnStatus)
				// setFlowSwitch(res.data.runStatus)
				setFlowStatus(res.data.runStatus)
				setStartUpTime(res.data.powerOnTime)
				dpdReadModeFunc()
			})
			.catch(err => {
				// Taro.hideLoading()
				Taro.showToast({
					title: err.msg,
					duration: 1000,
					icon: "error",
					mask: true
				})
			})
	}

	// 读取测量模式的函数
	const dpdReadModeFunc = async () => {
		let data = {
			devGId: router.params.devGId
		}
		await dpdReadModeApi(data)
			.then(res => {
				console.log("读取测量模式res", res)
				setCurrentMeasureMode(res.data.collectMode)
				setCurrentMeasureModeDefault(res.data.collectMode)
				setContinuousMeasureInterval(res.data.collectTime)
				setContinuousMeasureIntervalDefault(res.data.collectTime)
				// let hexS = res.data.hourCollectSet.toString()
				let times = getTimesFunc(res.data.hourCollectSet)
				console.log("times", times)

				setCheckedList(times)
				setCheckedListDefault(times)

				// Taro.hideLoading()
			})
			.catch(err => {
				// Taro.hideLoading()
				Taro.showToast({
					title: err.msg,
					duration: 1000,
					icon: "error",
					mask: true
				})
			})
	}

	// 流程开关Change事件
	const flowSwitchChange = e => {
		setFlowSwitch(e.target.value)
		console.log("修改流程开关状态", e.target.value)
		let flag = e.target.value ? 1 : 0
		saveDataFunc(1, flag)
	}

	// 模式名称匹配
	const modeNameMath = key => {
		let name
		switch (key) {
			case 0:
				name = "手动测量"

				break
			case 1:
				name = "连续测量"

				break
			case 2:
				name = "整点测量"

				break

			default:
				break
		}
		return name
	}

	// 模式选择Change事件
	const modeSelectChange = e => {
		console.log("当前选择模式", e.target.value)
		setCurrentMeasureMode(Number(e.target.value))
		saveDataFunc(2, e.target.value)
	}

	// 保存点击事件
	const saveClick = () => {
		let data = {
			flowStatus: flowSwitch ? 1 : 0,
			measureMode: currentMeasureMode,
			continuousMeasureInterval: continuousMeasureInterval
		}

		console.log("保存")
	}

	// 连续测量间隔事件change事件
	const continuousMeasureIntervalChange = e => {
		console.log("当前间隔时间", e)
		setContinuousMeasureInterval(e)
	}

	// 整点选择change事件
	function timeSelectChange(e) {
		setCheckedList(e)
	}

	// 整点选择保存点击事件
	const timesSaveClick = () => {
		console.log("保存数据", checkedList)
		let valueHex = getHexByTimes(checkedList)
		console.log("#valueHex", valueHex)

		saveDataFunc(4, valueHex)
	}

	// 测量间隔时间保存点击事件
	const intervalSaveClick = () => {
		// 判断和默认间隔时间是否是一样的
		if (continuousMeasureInterval != continuousMeasureIntervalDefault) {
			console.log("当前保存的间隔时间", continuousMeasureInterval)
			saveDataFunc(3, continuousMeasureInterval)
		}
	}

	// 流程开启点击事件
	const flowStartClick = () => {
		saveDataFunc(1, 1)
	}

	// 保存数据请求函数
	const saveDataFunc = async (typeId, value) => {
		console.log(typeId, value, "选择测量")

		Taro.showLoading({
			title: "加载中",
			mask: true
		})
		setTimeout(() => {
			Taro.hideLoading()
		}, 20000)
		let data = {
			devGId: router.params.devGId,
			typeId: typeId,
			value: value
		}
		console.log("保存数据", data)

		await setDpdDataApi(data)
			.then(res => {
				if (res.result == "success") {
					Taro.showToast({
						title: res.msg,
						duration: 1000,
						mask: true,
						icon: "success"
					})
				} else if (res.result == "error") {
					Taro.showToast({
						title: res.msg,
						duration: 1000,
						mask: true,
						icon: "error"
					})
				}
				dpdReadStatusFunc()
			})
			.catch(err => {
				Taro.showToast({
					title: err.msg,
					duration: 1000,
					mask: true,
					icon: "error"
				})
				// switch (typeId) {
				// 	case 1:
				// 		// setFlowSwitch(!flowSwitch)
				// 		break
				// 	case 2:
				// 		setCurrentMeasureMode(currentMeasureModeDefault)

				// 		break

				// 	case 3:
				// 		setContinuousMeasureInterval(continuousMeasureIntervalDefault)
				// 		break

				// 	case 4:
				// 		setCheckedList(checkedListDefault)
				// 		break

				// 	default:
				// 		break
				// }
				dpdReadStatusFunc()
			})
	}

	// 运行状态文本判断函数
	const runStatusTextFunc = () => {
		let text = ""
		switch (flowStatus) {
			case 0:
				text = "空闲"
				break
			case 1:
				text = "测量中"
				break
			case 2:
				text = "标定中"
				break
			case 3:
				text = "自清洗中"
				break
			case 4:
				text = "异常/手动停机"
				break
			case 5:
				text = "进水样中"
				break
			default:
				break
		}
		return text
	}

	// 报警状态文本判断函数
	const alarmTextFunc = () => {
		let text = ""
		switch (alarmStatus) {
			case 0:
				text = "无报警"
				break

			case 1:
				text = "试剂余量不足"
				break

			case 2:
				text = "试剂已用完"
				break

			case 3:
				text = "流通槽缺水"
				break

			case 4:
				text = "检测到漏液"
				break

			case 5:
				text = "自清洗无效"
				break

			case 6:
				text = "浓度超报警上限"
				break

			case 7:
				text = "浓度超报警下限"
				break

			case 8:
				text = "采样异常"
				break

			case 9:
				text = "水泵管缺水"
				break

			case 10:
				text = "水样池缺水"
				break

			case 11:
				text = "进试剂失败"
				break

			default:
				break
		}
		return text
	}

	return (
		<View className="fun_test_wrap">
			<View className="hanzi text-16 font-bold mt-14 mb-14 px-16">DPD控制</View>
			<View className="hanzi text-14 text-xx_text mb-14 px-16">
				您可以对设备DPD信息进行查看和配置
			</View>
			<View className="form_box">
				<View className="form_item">
					<Text className="label">运行状态</Text>
					<View className="right_box">
						<Text>{runStatusTextFunc()}</Text>
					</View>
				</View>

				<View className="form_item">
					<Text className="label">报警状态</Text>
					<View className="right_box">
						<Text>{alarmTextFunc()}</Text>
					</View>
				</View>

				<View className="form_item">
					<Text className="label">开机时间</Text>
					<View className="right_box">
						<Text>{startUpTime}</Text>
					</View>
				</View>
				<View className="form_item">
					<Text className="label">流程开关</Text>
					<View className="right_box">
						{/* <Switch
							className="flow_switch"
							color="#0f8af9"
							checked={flowSwitch}
							onChange={e => {
								flowSwitchChange(e)
							}}
						/> */}
						<Button
							type="primary"
							style="padding:0px 20px;background:#0f8af9;transform: scale(0.8);"
							onClick={flowStartClick}
						>
							启动
						</Button>
					</View>
				</View>
				<View className="form_item">
					<Text className="label">测量模式</Text>
					<View className="right_box">
						<Picker
							range={staticData.modeList}
							mode="selector"
							onChange={e => {
								modeSelectChange(e)
							}}
						>
							<View className="picker">
								{modeNameMath(currentMeasureMode)}
								<AtIcon
									value="chevron-right"
									size="20"
									color="#ccc"
									className="r_icon"
								></AtIcon>
							</View>
						</Picker>
					</View>
				</View>

				<View className="form_item ">
					<Text className="label">连续测量间隔</Text>
					<View className="right_box">
						<AtInputNumber
							min={0}
							max={599999}
							step={1}
							value={continuousMeasureInterval}
							onChange={e => {
								continuousMeasureIntervalChange(e)
							}}
						/>
						<Text className="unit">秒</Text>
						{/* 保存 */}
						<View
							className={`save_box ${
								continuousMeasureInterval == continuousMeasureIntervalDefault
									? "is_disabled"
									: ""
							}`}
							onClick={intervalSaveClick}
						>
							<AtIcon
								value="check-circle"
								size="36"
								color="#ffffff"
								className="r_icon"
							></AtIcon>
						</View>

						{/* <Button className="btn-max-w" type="primary" onClick={saveClick}>
							<AtIcon
								value="check-circle"
								size="20"
								color="#ffffff"
								className="r_icon"
							></AtIcon>
						</Button> */}
					</View>
				</View>
				{/* 整点测量时间选择 */}
				<View className="form_item">
					<Text className="label">整点选择</Text>
					<Button
						type="primary"
						style="padding:0px 20px;background:#0f8af9;transform: scale(0.8);"
						onClick={timesSaveClick}
					>
						保存
					</Button>
				</View>
				<br />
				<View className="right_box">
					{/* <View className="time_select_box">
						{timeAll.map(item => (
							<View className="time_item_box">{mathTimeFunc(item)}</View>
						))}
					</View> */}
					<AtCheckbox
						options={checkboxOption}
						selectedList={checkedList}
						onChange={e => {
							timeSelectChange(e)
						}}
					/>
				</View>
			</View>
			<View className="btn_box"></View>
		</View>
	)
}
export default observer(DpdControl)
